package com.pc.exception;


import com.pc.contants.GlobalConstants;
import com.pc.result.JSONResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public JSONResult handlerException(Exception e) {
        e.printStackTrace();
        return JSONResult.error(GlobalConstants.SYSTEM_ERR);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder stringBuilder = new StringBuilder();

        allErrors.forEach(a -> {
            String defaultMessage = a.getDefaultMessage();
            stringBuilder.append(defaultMessage).append(",");
        });
        return JSONResult.error(stringBuilder.toString());
    }
//    自定义的异常
    @ExceptionHandler(GlobalException.class)
    public JSONResult handlerMyException(GlobalException e) {
        e.printStackTrace();
        return JSONResult.error(e.getMessage());
    }
}
